import Vue from 'vue'
import axios from 'axios';
var qs = require('qs');
/**
 * 解析hash参数
 */
function getHashParameters() {
  var hashArr = location.hash
  if (hashArr.indexOf('?') > -1) {
    hashArr = hashArr.replace(hashArr.substr(0, hashArr.indexOf('?') + 1), '').split('&')
  }
  var params = {};
  for (var i = 0; i < hashArr.length; i++) {
    var data = hashArr[i].split("=");
    if (data.length == 2) {
      params[data[0]] = data[1];
    }
  }
  return params;
}

function getQV(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) { return pair[1]; }
  }
  return '';
}


// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 30000,                 // 请求超时时间
});

// request拦截器
service.interceptors.request.use(config => {
  let kv = getHashParameters()
  if (config.method === 'get' || config.method === 'GET') {
    if (!config.params) {
      config.params = {}
    }
    config.params.eid = kv.eid
    config.params.waid = kv.waid
    config.params.wwuid = kv.wwuid

    if (getQV('wxsb')) {
      config.params.wxsb = getQV('wxsb')
    }
    if (getQV('isflush')) {
      config.params.isflush = getQV('isflush')
    }
  } else if (config.method === 'post' || config.method === 'POST') {
    if (!config.data) {
      config.data = {}
    }
    config.data.eid = kv.eid
    config.data.waid = kv.waid
    config.data.wwuid = kv.wwuid
    if (getQV('wxsb')) {
      config.data.wxsb = getQV('wxsb')
    }
    if (getQV('isflush')) {
      config.data.isflush = getQV('isflush')
    }
    config.data = qs.stringify(config.data, { indices: false })
  }
  return config;
}, error => {
  // Do something with request error
  Promise.reject(error);
})

// respone拦截器
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.state !== 'ok') {
      if (res.msg) {
        Vue.$vux.alert.show({
          title: '提示信息',
          content: res.msg,
        })
      }
      return Promise.reject(res.msg);
    } else {
      return res;
    }
  },
  error => {
    // Vue.$vux.alert.show({
    // title: '提示信息',
    // content: '连接服务器出错，请稍后再试',
    // content: error.response+'------------'+error.code,
    // })
    return Promise.reject(error);
  }
)

export default service;
